package com.yy.app.config.custom;

import com.nimbusds.jose.util.Base64URL;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;

/**
 * @Description 自定义令牌响应客户端
 * @Date 2025/10/11 上午10:15
 * @Author yanglin
 **/
public class CustomAuthorizationCodeTokenResponseClient implements OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> {
    @Override
    public OAuth2AccessTokenResponse getTokenResponse(OAuth2AuthorizationCodeGrantRequest authorizationGrantRequest) {
        String authorization = authorizationGrantRequest.getClientRegistration().getClientId() + ":" + authorizationGrantRequest.getClientRegistration().getClientSecret();
        // 创建WebClient
        WebClient webClient = WebClient.builder()
                .baseUrl(authorizationGrantRequest.getClientRegistration().getProviderDetails().getTokenUri())
                .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader("Authorization", "Basic " + Base64URL.encode(authorization))
                .build();

        // 准备请求参数
        MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
        formParameters.add("grant_type", authorizationGrantRequest.getGrantType().getValue());
        formParameters.add("code", authorizationGrantRequest.getAuthorizationExchange().getAuthorizationResponse().getCode());
        formParameters.add("redirect_uri", authorizationGrantRequest.getAuthorizationExchange().getAuthorizationRequest().getRedirectUri());
        formParameters.add("client_id", authorizationGrantRequest.getClientRegistration().getClientId());
        formParameters.add("client_secret", authorizationGrantRequest.getClientRegistration().getClientSecret());
        // 发送请求
        return webClient.post()
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .body(BodyInserters.fromFormData(formParameters))
                .retrieve()
                .bodyToMono(OAuth2AccessTokenResponse.class)
                .block();
    }
}
